﻿using _537AppStore_API.Data;
using _537AppStore_API.Model;

//using _537AppStore_API.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace _537AppStore_API.Controller
{
    [Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
    [ApiController]
    public class CommandController : ControllerBase
    {
        public readonly AppDbContext _db;
        public CommandController(AppDbContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 获取所有命令
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Command>>> GetCommands()
        {
            return await _db.Command.ToListAsync();
        }

        /// <summary>
        /// 创建命令
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<ActionResult<Command>> PostCommand(Command command)
        {
            command.id = Guid.NewGuid();
            command.CreateTime = DateTime.Now;
            _db.Command.Add(command);
            await _db.SaveChangesAsync();

            // 返回 201 Created 及新创建的资源地址
            return CreatedAtAction(nameof(GetCommands), new { Name = command.CommandName }, command);
        }
        /// <summary>
        /// 更新命令
        /// </summary>
        /// <param name="Name"></param>
        /// 
        [HttpPut("{id}")]
        public async Task<IActionResult> PutCommand(string Name, Command command)
        {
            if (Name != command.CommandName)
            {
                return BadRequest();
            }
            _db.Entry(command).State = EntityState.Modified;
            command.CreateTime = DateTime.Now;
            try
            {
                await _db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CommandExists(Name))
                {
                    return NotFound();
                }
                throw;
            }
            return NoContent();// 204 无内容
        }

        private bool CommandExists(string name)
        {
            return _db.Command.Any(e => e.CommandName == name);
        }
        /// <summary>
        /// 删除命令
        /// </summary>
        /// 
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCommand(Guid id)
        {
            var command = await _db.Command.FindAsync(id);
            if (command == null)
            {
                return NotFound();
            }
            _db.Command.Remove(command);
            await _db.SaveChangesAsync();
            return NoContent();
        }
    }
}
